package com.share.tool;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * author:caifan
 * date:2019/11/27
 */
public class ReadSchema {

    public static final String URL = "jdbc:mysql://47.97.185.214:3306/goodstone?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    public static final String USERNAME = "goodstone";
    public static final String PASSWORD = "jAPayC";
    public static final String DRIVER_NAME = "com.jdbc.mysql.Driver";

    @Test
    public void test() throws Exception {
        List<String> allTables = getAllTables();
        for (String table : allTables) {
            System.out.println(convertEntityName(table));
        }
    }

    public Connection getConnection() throws Exception{
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    /**
     * 获取所有的表名
     * @return
     * @throws Exception
     */
    public List<String> getAllTables() throws Exception {
        List<String> tableList = new ArrayList<>();
        Connection connection = getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
        while (tables.next()) {
            tableList.add(tables.getString(3));
        }
        return tableList;
    }

    /**
     * 将数据库表名转成实体名
     */
    public String convertEntityName(String tableName) {
        String[] tableNames = tableName.split("_");
        StringBuffer entityName = new StringBuffer();
        for (String table : tableNames) {
            entityName.append(table.substring(0,1).toUpperCase()).append(table.substring(1));
        }
        return entityName.toString().trim();
    }
}
